<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  getSalaryStandardList,
  getSalaryStandardDetail,
  registerSalaryPay,
  getPayEmployees,
  calculateSalaryPay,
} from '@/api/salary'
import { getOrganizationOptions } from '@/api/system'

const formRef = ref()
const formData = ref({
  employeeRange: undefined, // 员工范围（机构ID）
  standardId: undefined, // 薪酬标准ID
})

// 表格列定义
const columns = [
  { title: '员工编号', dataIndex: 'employeeCode', key: 'employeeCode', width: 100, fixed: 'left' },
  { title: '姓名', dataIndex: 'employeeName', key: 'employeeName', width: 80, fixed: 'left' },
  { title: '基本工资', dataIndex: 'baseSalary', key: 'baseSalary', width: 100 },
  { title: '岗位工资', dataIndex: 'positionSalary', key: 'positionSalary', width: 100 },
  { title: '津贴补贴', dataIndex: 'allowance', key: 'allowance', width: 100 },
  { title: '应发合计', dataIndex: 'totalPay', key: 'totalPay', width: 100 },
  { title: '社保扣款', dataIndex: 'socialSecurity', key: 'socialSecurity', width: 100 },
  { title: '公积金扣款', dataIndex: 'housingFund', key: 'housingFund', width: 110 },
  { title: '个税', dataIndex: 'tax', key: 'tax', width: 80 },
  { title: '其他扣除', dataIndex: 'deduction', key: 'deduction', width: 100 },
  { title: '实发金额', dataIndex: 'actualPay', key: 'actualPay', width: 100, fixed: 'right' },
]

const dataSource = ref([])
const loading = ref(false)

// 机构选项
const organizationOptions = ref([])
const organizationLoading = ref(false)

// 薪酬标准选项
const standardOptions = ref([])
const standardLoading = ref(false)

// 员工列表（根据范围获取）
const employeeList = ref([])
const employeeLoading = ref(false)

// 当前选中的薪酬标准详情
const currentStandardDetail = ref(null)

// 获取机构选项
const fetchOrganizationOptions = async () => {
  organizationLoading.value = true
  try {
    const response = await getOrganizationOptions()
    if (response && Array.isArray(response.list)) {
      // 接口返回的数据结构已经是 { value, label }，直接使用
      organizationOptions.value = response.list.map((item) => ({
        value: item.value,
        label: item.label,
        level: item.level, // 保留 level 信息，可能后续会用到
      }))
      // 添加"全部"选项
      organizationOptions.value.unshift({ value: '全部', label: '全部人员' })
    } else {
      organizationOptions.value = [{ value: '全部', label: '全部人员' }]
    }
  } catch (error) {
    console.error('获取机构选项失败:', error)
    // 如果接口失败，至少提供"全部"选项
    organizationOptions.value = [{ value: '全部', label: '全部人员' }]
  } finally {
    organizationLoading.value = false
  }
}

// 获取薪酬标准列表
const fetchStandardOptions = async () => {
  standardLoading.value = true
  try {
    const response = await getSalaryStandardList({ page: 1, pageSize: 100 })
    console.log('薪酬标准列表响应:', response)

    if (response && Array.isArray(response.list)) {
      standardOptions.value = response.list
        .filter((item) => item && item.id) // 过滤掉无效项
        .map((item) => {
          // 接口返回的字段是 standardCode 和 standardName，兼容 code 和 name
          const code = item.standardCode || item.code || '未知编号'
          const name = item.standardName || item.name || '未知名称'
          // 确保 value 是数字类型，与接口返回的 id 类型一致
          const optionValue = typeof item.id === 'number' ? item.id : Number(item.id)
          return {
            value: optionValue,
            label: `${code} - ${name}`,
            id: item.id,
            code: item.standardCode || item.code,
            name: item.standardName || item.name,
          }
        })
      console.log('薪酬标准选项:', standardOptions.value)
      console.log('薪酬标准选项数量:', standardOptions.value.length)
    } else {
      console.warn('薪酬标准列表数据格式异常:', response)
      standardOptions.value = []
    }
  } catch (error) {
    console.error('获取薪酬标准列表失败:', error)
    standardOptions.value = []
  } finally {
    standardLoading.value = false
  }
}

// 根据员工范围获取员工列表
const fetchEmployeeList = async (range) => {
  // 如果没有选择机构，不请求
  if (!range) {
    employeeList.value = []
    return
  }

  employeeLoading.value = true
  try {
    // 准备请求参数
    const params = {}

    // 如果选择了机构（不是"全部"），则传递机构参数
    if (range && range !== '全部') {
      // 查找机构选项，获取机构名称（label）而不是 value
      const selectedOrg = organizationOptions.value.find((opt) => opt.value === range)
      if (selectedOrg) {
        // 使用机构的 label（名称）作为参数
        params.organization = selectedOrg.label
      } else {
        // 如果找不到，直接使用 range 的值
        params.organization = range
      }
    }

    // 调用接口获取可发薪员工列表
    const response = await getPayEmployees(params)

    console.log('获取可发薪员工列表响应:', response)

    // 接口返回的数据处理
    // 根据 request.js 的响应拦截器，会返回 res.data
    // 如果接口返回 { code: 0, data: [...] }，则 response 就是数组
    // 如果接口返回 { code: 0, data: { list: [...] } }，则需要取 response.list
    if (Array.isArray(response)) {
      employeeList.value = response.map((item) => ({
        id: item.id,
        code: item.code,
        name: item.name,
        organization: item.organization,
        position: item.position,
      }))
      console.log('员工列表加载成功，共', employeeList.value.length, '人')
    } else if (response && Array.isArray(response.list)) {
      // 如果返回的是对象，包含 list 字段
      employeeList.value = response.list.map((item) => ({
        id: item.id,
        code: item.code,
        name: item.name,
        organization: item.organization,
        position: item.position,
      }))
      console.log('员工列表加载成功，共', employeeList.value.length, '人')
    } else {
      console.warn('接口返回数据格式异常:', response)
      employeeList.value = []
      if (response && typeof response === 'object') {
        message.warning('未找到可发薪员工，请检查机构选择')
      }
    }
  } catch (error) {
    console.error('获取可发薪员工列表失败:', error)
    employeeList.value = []
    message.error('获取可发薪员工列表失败')
  } finally {
    employeeLoading.value = false
  }
}

// 处理员工范围变化
const handleEmployeeRangeChange = async (value) => {
  formData.value.employeeRange = value
  // 清空薪酬标准选择和表格数据
  formData.value.standardId = undefined
  currentStandardDetail.value = null
  dataSource.value = []

  // 如果选择了机构，则获取员工列表
  if (value) {
    await fetchEmployeeList(value)
  } else {
    employeeList.value = []
  }
}

// 处理薪酬标准选择变化
const handleStandardChange = async (value) => {
  console.log('选择薪酬标准:', value)
  formData.value.standardId = value
  currentStandardDetail.value = null
  dataSource.value = []

  if (!value) {
    return
  }

  // 如果员工列表为空，给出提示但允许继续（可能员工列表还在加载或确实为空）
  if (!employeeList.value || employeeList.value.length === 0) {
    message.warning('当前没有可发薪员工，请检查机构选择，或等待员工列表加载完成')
    // 不阻止选择，允许用户先选择标准，等员工列表加载后再生成表格
    // 如果确实没有员工，后续在生成表格时会处理
  }

  loading.value = true
  try {
    const response = await getSalaryStandardDetail(value)
    console.log('薪酬标准详情响应:', response)
    currentStandardDetail.value = response

    // 检查是否有员工列表
    if (!employeeList.value || employeeList.value.length === 0) {
      message.warning('当前没有可发薪员工，无法生成发放明细。请检查机构选择')
      loading.value = false
      return
    }

    console.log('员工列表数量:', employeeList.value.length)

    // 根据标准详情和员工列表生成表格数据
    if (response && response.items && Array.isArray(response.items)) {
      // 将标准详情中的 items 转换为键值对，方便查找
      const standardItemsMap = {}
      response.items.forEach((item) => {
        const key = item.itemName
        standardItemsMap[key] = item.amount || 0
      })

      // 为每个员工生成一行数据
      dataSource.value = employeeList.value.map((employee) => {
        // 从标准详情中获取各项金额
        const baseSalary = standardItemsMap['基本工资'] || 0
        const positionSalary = standardItemsMap['岗位工资'] || 0
        const allowance =
          (standardItemsMap['津贴'] || 0) +
          (standardItemsMap['交通补贴'] || 0) +
          (standardItemsMap['餐费补贴'] || 0)
        const socialSecurity = standardItemsMap['社保'] || 0
        const housingFund = standardItemsMap['公积金'] || 0
        const tax = standardItemsMap['个税'] || 0

        // 计算应发合计
        const totalPay = baseSalary + positionSalary + allowance
        // 其他扣除默认为0，用户可编辑
        const deduction = 0
        // 实发金额由计算接口返回，初始为空
        const actualPay = null

        return {
          key: employee.id,
          employeeCode: employee.code,
          employeeName: employee.name,
          baseSalary,
          positionSalary,
          allowance,
          totalPay,
          socialSecurity,
          housingFund,
          tax,
          deduction,
          actualPay,
        }
      })

      console.log('生成的表格数据:', dataSource.value)
      console.log('表格数据数量:', dataSource.value.length)
      message.success('已加载薪酬标准，请填写其他扣除项')
    } else {
      message.warning('薪酬标准详情数据不完整')
    }
  } catch (error) {
    console.error('获取薪酬标准详情失败:', error)
    message.error('获取薪酬标准详情失败')
    formData.value.standardId = undefined
  } finally {
    loading.value = false
  }
}

// 处理扣除项变化（不自动计算实发金额，由计算接口返回）
const handleDeductionChange = (record, value) => {
  record.deduction = value || 0
}

// 清空表单和表格数据
const handleClear = () => {
  formData.value = {
    employeeRange: undefined,
    standardId: undefined,
  }
  dataSource.value = []
  employeeList.value = []
  currentStandardDetail.value = null
  message.info('已清空表单数据')
}

// 提交登记
const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    // 验证必填项
    if (!formData.value.employeeRange) {
      message.warning('请选择员工范围')
      return
    }

    if (!formData.value.standardId) {
      message.warning('请选择薪酬标准')
      return
    }

    if (dataSource.value.length === 0) {
      message.warning('请先选择薪酬标准以生成发放明细')
      return
    }

    // 获取员工范围显示名称
    const selectedOrg = organizationOptions.value.find(
      (opt) => opt.value === formData.value.employeeRange,
    )
    const employeeRangeName = selectedOrg ? selectedOrg.label : formData.value.employeeRange

    // 准备提交数据（按照接口文档格式，不包含 actualPay，由计算接口返回）
    const submitData = {
      employeeRange: employeeRangeName,
      list: dataSource.value.map((item) => ({
        employeeCode: item.employeeCode,
        employeeName: item.employeeName,
        baseSalary: item.baseSalary || 0,
        positionSalary: item.positionSalary || 0,
        allowance: item.allowance || 0,
        totalPay: item.totalPay || 0,
        socialSecurity: item.socialSecurity || 0,
        housingFund: item.housingFund || 0,
        tax: item.tax || 0,
        deduction: item.deduction || 0,
        // actualPay 由计算接口返回，不在此提交
      })),
    }

    console.log('提交薪酬发放登记数据:', submitData)

    loading.value = true
    try {
      const response = await registerSalaryPay(submitData)
      console.log('薪酬发放登记响应:', response)

      // 登记成功后调用计算接口获取计算后的数据（包括实发金额）
      try {
        const calculateData = await calculateSalaryPay({
          employeeRange: employeeRangeName,
        })
        console.log('薪酬计算响应:', calculateData)

        // 用计算接口返回的数据更新表格
        if (calculateData && calculateData.list && Array.isArray(calculateData.list)) {
          console.log('计算接口返回的列表:', calculateData.list)
          console.log('当前表格数据:', dataSource.value)

          // 更新 dataSource 中的计算后的数据
          // 如果计算接口返回的 code 不为空，优先通过 code 匹配；否则按索引顺序匹配
          dataSource.value = dataSource.value.map((item, index) => {
            let calculated = null

            // 优先通过 code 匹配
            if (item.employeeCode) {
              calculated = calculateData.list.find((calc) => calc.code === item.employeeCode)
            }

            // 如果通过 code 匹配不到，且计算接口返回的 code 为 null，则按索引匹配
            if (!calculated && index < calculateData.list.length) {
              calculated = calculateData.list[index]
            }

            if (calculated) {
              return {
                ...item,
                baseSalary:
                  calculated.baseSalary !== undefined ? calculated.baseSalary : item.baseSalary,
                positionSalary:
                  calculated.positionSalary !== undefined
                    ? calculated.positionSalary
                    : item.positionSalary,
                allowance:
                  calculated.allowance !== undefined ? calculated.allowance : item.allowance,
                totalPay: calculated.totalPay !== undefined ? calculated.totalPay : item.totalPay,
                socialSecurity:
                  calculated.socialSecurity !== undefined
                    ? calculated.socialSecurity
                    : item.socialSecurity,
                housingFund:
                  calculated.housingFund !== undefined ? calculated.housingFund : item.housingFund,
                tax: calculated.tax !== undefined ? calculated.tax : item.tax,
                deduction:
                  calculated.deduction !== undefined ? calculated.deduction : item.deduction,
                actualPay:
                  calculated.actualPay !== undefined ? calculated.actualPay : item.actualPay, // 更新实发金额
              }
            }
            return item
          })

          console.log('更新后的表格数据:', dataSource.value)
          message.success('薪酬发放登记成功，已计算实发金额')
        } else {
          message.success('薪酬发放登记成功，已提交复核')
        }
      } catch (calcError) {
        console.error('计算薪酬失败:', calcError)
        message.success('薪酬发放登记成功，但计算薪酬失败，请稍后重试')
      }
    } catch (error) {
      console.error('提交登记失败:', error)
      // handleApiError 已经处理了错误提示
    } finally {
      loading.value = false
    }
  } catch (err) {
    if (err?.errorFields) {
      return
    }
    message.error('提交失败，请稍后重试')
  }
}

onMounted(() => {
  fetchOrganizationOptions()
  fetchStandardOptions()
})
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">薪酬发放登记</h1>
      <p class="page-desc">月度薪酬数据的计算和录入，选择员工范围和薪酬标准后自动填充数据</p>
    </div>

    <div class="page-content">
      <a-card class="form-card">
        <a-form
          ref="formRef"
          :model="formData"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
        >
          <a-card title="发放信息" class="section-card" :bordered="false">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="员工范围"
                  name="employeeRange"
                  :rules="[{ required: true, message: '请选择员工范围' }]"
                >
                  <a-select
                    v-model:value="formData.employeeRange"
                    placeholder="请选择员工范围"
                    style="width: 100%"
                    :loading="organizationLoading"
                    @change="handleEmployeeRangeChange"
                  >
                    <a-select-option
                      v-for="option in organizationOptions"
                      :key="option.value"
                      :value="option.value"
                    >
                      {{ option.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="薪酬标准"
                  name="standardId"
                  :rules="[{ required: true, message: '请选择薪酬标准' }]"
                >
                  <a-select
                    v-model:value="formData.standardId"
                    placeholder="请先选择员工范围，再选择薪酬标准"
                    style="width: 100%"
                    :loading="standardLoading"
                    :disabled="!formData.employeeRange"
                    @change="handleStandardChange"
                  >
                    <a-select-option
                      v-for="option in standardOptions"
                      :key="option.value"
                      :value="option.value"
                    >
                      {{ option.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <div class="form-actions-inline">
              <a-button :loading="loading" @click="handleClear">清空</a-button>
              <a-button type="primary" :loading="loading" @click="handleSubmit">提交登记</a-button>
            </div>
          </a-card>

          <a-card title="发放明细" class="section-card" :bordered="false">
            <a-table
              :columns="columns"
              :data-source="dataSource"
              :loading="loading"
              :pagination="{ pageSize: 10 }"
              :scroll="{ x: 1100 }"
            >
              <template #bodyCell="{ column, record }">
                <!-- 金额列显示 -->
                <template
                  v-if="
                    [
                      'baseSalary',
                      'positionSalary',
                      'allowance',
                      'totalPay',
                      'socialSecurity',
                      'housingFund',
                      'tax',
                    ].includes(column.key)
                  "
                >
                  <span style="text-align: right; display: block"
                    >¥{{ (record[column.key] || 0).toLocaleString() }}</span
                  >
                </template>
                <!-- 其他扣除列可编辑 -->
                <template v-if="column.key === 'deduction'">
                  <a-input-number
                    v-model:value="record.deduction"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                    placeholder="0.00"
                    @change="(value) => handleDeductionChange(record, value)"
                  >
                    <template #prefix>¥</template>
                  </a-input-number>
                </template>
                <!-- 实发金额列只显示（由计算接口返回） -->
                <template v-if="column.key === 'actualPay'">
                  <span style="text-align: right; display: block">{{
                    record.actualPay !== null && record.actualPay !== undefined
                      ? `¥${record.actualPay.toLocaleString()}`
                      : '待计算'
                  }}</span>
                </template>
              </template>
            </a-table>
          </a-card>
        </a-form>
      </a-card>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-desc {
  font-size: 14px;
  color: #86868b;
  margin: 0;
}

.page-content {
  margin-top: 24px;
}

.form-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
  border: none;
}

.section-card {
  margin-bottom: 24px;
  background: #fafafa;
  border-radius: 8px;
}

.section-card :deep(.ant-card-head) {
  background: transparent;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  padding: 16px 24px;
}

.section-card :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
  color: #1d1d1f;
}

.section-card :deep(.ant-card-body) {
  padding: 24px;
}

.form-actions-inline {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
}
</style>
